package com.ljb.lib_http.okgo;

import android.app.Application;


import com.ljb.lib_http.HttpCallback;
import com.ljb.lib_http.HttpLoader;
import com.ljb.lib_http.HttpParams;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.Response;

import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * Created by ljb on 2018/6/21.
 */
public class OkgoHttpLoader implements HttpLoader {

    public OkgoHttpLoader(Application application) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BASIC);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        //https相关设置
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);//信任所有证书,不安全有风险
        //配置OkGo
        OkGo.getInstance().init(application)                            //必须调用初始化
                .setOkHttpClient(builder.build())               //必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(0);                              //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
    }

    @Override
    public <T> void get(String url, HttpParams httpParams, Object tag, Class<T> clazz, final HttpCallback<T> httpCallback) {
        OkGo.<T>get(url)
                .tag(url)
                .params(getParams(httpParams))
                .execute(new JsonCallback<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (httpCallback != null)
                            httpCallback.onSucess(response.body());
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        if (httpCallback != null)
                            httpCallback.onError();
                    }
                });
    }

    @Override
    public <T> void get(String url, HttpParams httpParams, Object tag, Type type, final HttpCallback<T> httpCallback) {
        OkGo.<T>get(url)
                .tag(url)
                .params(getParams(httpParams))
                .execute(new JsonCallback<T>(type) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (httpCallback != null)
                            httpCallback.onSucess(response.body());
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        if (httpCallback != null)
                            httpCallback.onError();
                    }
                });
    }

    @Override
    public <T> void post(String url, HttpParams httpParams, Object tag, Class<T> clazz, final HttpCallback<T> httpCallback) {
        OkGo.<T>post(url)
                .tag(url)
                .params(getParams(httpParams))
                .execute(new JsonCallback<T>(clazz) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (httpCallback != null)
                            httpCallback.onSucess(response.body());
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        if (httpCallback != null)
                            httpCallback.onError();
                    }
                });
    }

    @Override
    public <T> void post(String url, HttpParams httpParams, Object tag, Type type, final HttpCallback<T> httpCallback) {
        OkGo.<T>post(url)
                .tag(url)
                .params(getParams(httpParams))
                .execute(new JsonCallback<T>(type) {
                    @Override
                    public void onSuccess(Response<T> response) {
                        if (httpCallback != null)
                            httpCallback.onSucess(response.body());
                    }

                    @Override
                    public void onError(Response<T> response) {
                        super.onError(response);
                        if (httpCallback != null)
                            httpCallback.onError();
                    }
                });
    }

    @Override
    public void stop(Object tag) {
        OkGo.getInstance().cancelTag(tag);
    }

    @Override
    public void stopAll() {
        OkGo.getInstance().cancelAll();
    }

    //整理参数
    private com.lzy.okgo.model.HttpParams getParams(HttpParams httpParams) {
        com.lzy.okgo.model.HttpParams params = null;
        if (httpParams != null) {
            params = new com.lzy.okgo.model.HttpParams();
            for (Map.Entry<String, String> urlParam : httpParams.getUrlParamsMap().entrySet()) {
                params.put(urlParam.getKey(), urlParam.getValue());
            }
        }
        return params;
    }
}
